package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * 用户服务
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    //根据用户名查询数据库用户信息和关联的信息，同时需要查询角色关联的权限信息

    public User findByUserName(String username) {
        //查询用户基本信息
        User user = userMapper.findByUserName(username);
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        Set<Role> roles = roleMapper.findByUserId(userId);

        for (Role role : roles) {
            Integer roleId = role.getId();

            Set<Permission> permissions = permissionMapper.findByRoleId(roleId);
            role.setPermissions(permissions);
        }
        user.setRoles(roles);//让用户关联角色
        return user;
    }
}
